#include	"lp_global_vars.h"

int ipmulti_send(int sock, inst *i_msg, int msg_size, struct sockaddr_in* addr);
//------------------------------------------------------------------------------
int create_ip_multicast_sender_socket(const char *ip) {

	struct ip_mreq multi;
	int ipm_sid = socket(AF_INET, SOCK_DGRAM, 0);
	assert(ipm_sid >= 0);

	multi.imr_multiaddr.s_addr = inet_addr(ip);
	return ipm_sid;
}
//------------------------------------------------------------------------------
int create_ip_multicast_receiver_socket(const char *multicast_ip, const char *self_ip, const int port) {

	struct sockaddr_in ipm_addr;
	struct ip_mreq mreq;
	int activate = 1, status;

	int ipm_sid = socket(AF_INET, SOCK_DGRAM, 0);
	assert(ipm_sid >= 0);
	status = setsockopt(ipm_sid, SOL_SOCKET, SO_REUSEADDR, &activate, sizeof(int));
	assert(status == 0);

	ipm_addr.sin_family = AF_INET;
	ipm_addr.sin_addr.s_addr = inet_addr(multicast_ip);//inet_addr(ip);// u can change ip to INADDR_ANY
	ipm_addr.sin_port = htons(port);

	status = bind(ipm_sid, (struct sockaddr*) &ipm_addr, sizeof(ipm_addr));
	assert(status >= 0);

	mreq.imr_multiaddr.s_addr = inet_addr(multicast_ip);
	mreq.imr_interface.s_addr = INADDR_ANY;//inet_addr(ip2);//INADDR_ANY;//;//;this uses the default NIC on the system.

	status = setsockopt(ipm_sid, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq));
	assert(status >= 0);

	int flag = fcntl(ipm_sid, F_GETFL);
	assert(flag >= 0);
	flag |= O_NONBLOCK;
	if (fcntl(ipm_sid, F_SETFL, flag) < 0) {
		perror("fcntl2");
		return -1;
	}
	return ipm_sid;
}
//------------------------------------------------------------------------------
struct sockaddr_in * getAddr(int port, const char *ip) {

	struct sockaddr_in *address;
	address = (struct sockaddr_in *) malloc(sizeof(struct sockaddr));
	memset(address, '\0', sizeof(struct sockaddr_in));

	address->sin_family = AF_INET;
	address->sin_addr.s_addr = inet_addr(ip);
	address->sin_port = htons(port);

	return address;
}
//------------------------------------------------------------------------------
int ipmulti_send(int sock, inst *i_msg, int msg_size, struct sockaddr_in* addr) {
	int cnt = -1;
	cnt = sendto(sock, i_msg, msg_size, MSG_WAITALL, (struct sockaddr *) addr, sizeof(struct sockaddr_in));
	return cnt;
}

